package net.trade.trade.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.core.base.struts.BaseAction;
import net.core.common.HttpUtil;
import net.core.common.StrUtils;
import net.core.common.SysConfigUtil;
import net.sf.json.JSONArray;
import net.system.sys.service.ICommService;
import net.trade.common.TradeUtils;
import net.trade.trade.service.IFundService;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;

@Scope("request")
@Namespace("/trade")
@InterceptorRefs(@InterceptorRef("basicStack"))
@ParentPackage("struts-default")
@Results({ @Result(name = "error", location = "/error.jsp") })
public class FundAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8099816401800218571L;
	final Logger logger = LoggerFactory.getLogger(FundAction.class);
	@Autowired
	private ICommService commService;
	private List<HashMap> listmap;// 返回的列表
	private HashMap<String, String> hmRetrun= new HashMap<String, String>();// 返回的HashMap

	private HashMap<String, String> param = new HashMap<String, String>();

	private List resultList;

	@Autowired
	private IFundService service;

	public List<HashMap> getListmap() {
		return listmap;
	}

	public void setListmap(List<HashMap> listmap) {
		this.listmap = listmap;
	}

	public HashMap<String, String> getHmRetrun() {
		return hmRetrun;
	}

	public void setHmRetrun(HashMap<String, String> hmRetrun) {
		this.hmRetrun = hmRetrun;
	}

	public HashMap<String, String> getParam() {
		return param;
	}

	public void setParam(HashMap<String, String> param) {
		this.param = param;
	}

	public List getResultList() {
		return resultList;
	}

	public void setResultList(List resultList) {
		this.resultList = resultList;
	}

	/**
	 * 资金明细
	 * 
	 * @return
	 */
	@Action(value = "flows", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/fund/customerFund.jsp") })
	public String flows() {
		//
		// HttpServletRequest request = getRequest();
		// HttpSession session = getSession();

		// 加载行情数据
		// HashMap reqMap = new HashMap();
		// reqMap = HttpUtil.buildParameterMap(getRequest());
		// logger.debug(reqMap.toString());
		// listmap = service.selectUserFundflow(reqMap);
		// MiyinMarket market = service.getMarket();
		// request.setAttribute("market", market);

		return SUCCESS;
	}

	/**
	 * 查询资金往来信息列表
	 * 
	 * @return
	 */
	@Action(value = "userFundList")
	public void userFundList() {
		try {
			String userId = (String) getSession().getAttribute("userId");
			if (StringUtils.isNotEmpty(userId)) {
				param.put("userId", userId);
				resultList = service.userFundList(param);
				JSONArray json = JSONArray.fromObject(resultList);

				logger.info("查询购卡信息列表成功！");
				TradeUtils.ajaxStr(getResponse(), json.toString());
			} else {
				logger.info("获取用户ID失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("查询购卡信息列表失败！");
		}
		//return "userFundList";
	}

	/**
	 * 查询资金往来信息总数
	 * 
	 * @return
	 */
	@Action(value = "userFundCount")
	public void userFundCount() {
		try {
			String userId = (String) getSession().getAttribute("userId");
			if (StringUtils.isNotEmpty(userId)) {
				param.put("userId", userId);
				resultList = service.userFundCount(param);
				logger.info("查询购卡信息总数成功！");
				JSONArray json = JSONArray.fromObject(resultList);
				TradeUtils.ajaxStr(getResponse(), json.toString());
			} else {
				logger.info("获取用户ID失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("查询购卡信息总数失败！");
		}
		//return "userFundCount";
	}
	
	/**
	 * 资金管理
	 * 
	 * @return
	 */
	@Action(value = "fundManage", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/fund/ManageFund.jsp") })
	public String fundManage() {
		return SUCCESS;
	}
	
	/**
	 * 管理资金信息列表
	 * 
	 * @return
	 */
	@Action(value = "manageFundList")
	public void manageFundList() {
		try {
			resultList = service.manageFundList(param);
			JSONArray json = JSONArray.fromObject(resultList);

			logger.info("查询管理资金信息列表成功！");
			TradeUtils.ajaxStr(getResponse(), json.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("查询管理资金信息列表失败！");
		}
		//return "userFundList";
	}
	
	/**
	 * 管理资金信息 总数
	 * 
	 * @return
	 */
	@Action(value = "manageFundCount")
	public void manageFundCount() {
		try {
			resultList = service.manageFundCount(param);
			JSONArray json = JSONArray.fromObject(resultList);

			logger.info("查询管理资金信息总数成功！");
			TradeUtils.ajaxStr(getResponse(), json.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("查询管理资金信息总数失败！");
		}
		//return "userFundList";
	}

	@Action(value = "fundData")
	public void fundData() {
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		logger.debug(reqMap.toString());
		listmap = service.selectUserFundflow(reqMap);
	}

	@Action(value = "fundDataCount")
	public void fundDataCount() {
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		logger.debug(reqMap.toString());
		listmap = service.userFundCount(reqMap);
	}

	/**
	 * 充值
	 * 
	 * @return
	 */
	@Action(value = "recharge", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/trade/recharge.jsp") })
	public String recharge() {
		//
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(request);
		
		return SUCCESS;
	}
	
	/**
	 * 手动充值
	 * 
	 * @return
	 */
	@Action(value = "rechargeM", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/trade/rechargeM.jsp") })
	public String rechargeM() {
		//
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(request);
		Iterator iter = param.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object key = entry.getKey();
			Object val = entry.getValue();
			hmRetrun.put("in_"+key, (String) val);
		}
		return SUCCESS;
	}
	
	@Action(value = "fundNotify", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/fund/notify_url.jsp") })
	public String fundNotify() {
		//
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();
		// HashMap reqMap = new HashMap();
		// reqMap = HttpUtil.buildParameterMap(getRequest());

		return SUCCESS;
	}
	
	@Action(value = "fundReturn", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/fund/return_url.jsp") })
	public String fundreturn() {
		//
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();
		 HashMap reqMap = new HashMap();
		 reqMap = HttpUtil.buildParameterMap(getRequest());
		 String result = service.fundReturn(reqMap);
		return SUCCESS;
	}
	

	@Action(value = "rechargeAdd", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/fund/fundAlipay.jsp") })
	public String rechargeAdd() {
		HttpServletRequest request = getRequest();
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		//支付类型
		String payment_type = "1";
		//必填，不能修改
		//服务器异步通知页面路径
		String notify_url = "http://localhost:8101/web/trade/fundNotify.shtml";
		//需http://格式的完整路径，不能加?id=123这类自定义参数

		//页面跳转同步通知页面路径
		//http://www.xxx.com/create_direct_pay_by_user-JAVA-UTF-8/return_url.jsp
		String return_url = "http://localhost:8101/web/trade/fundReturn.shtml";
		//需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

		//卖家支付宝帐户
		String seller_email = SysConfigUtil.getConfigValue("TRADE_ALIPAY", "TRADECFG");
		//必填

		//商户订单号
		String out_trade_no = System.currentTimeMillis()+commService.getSeq("fund"); ;
		//商户网站订单系统中唯一订单号，必填

		//订单名称
		String subject = SysConfigUtil.getConfigValue("TRADE_ALIPAY_SUBJECT", "TRADECFG");
		//必填

		//付款金额
		String total_fee = StrUtils.getNotNullStrValue(reqMap.get("amount"));
		//必填

		//订单描述

		//String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
		//商品展示地址
		//String show_url = new String(request.getParameter("WIDshow_url").getBytes("ISO-8859-1"),"UTF-8");
		//需以http://开头的完整路径，例如：http://www.xxx.com/myorder.html

		//防钓鱼时间戳
		String anti_phishing_key = "";
		//若要使用请调用类文件submit中的query_timestamp函数

		//客户端的IP地址
		String exter_invoke_ip = "";
		//非局域网的外网IP地址，如：221.0.0.1
		
		
		//////////////////////////////////////////////////////////////////////////////////
		
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("seller_email", seller_email);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", total_fee);
		//sParaTemp.put("body", body);
		//sParaTemp.put("show_url", show_url);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		HttpSession session = getSession();
		String userId = (String) session.getAttribute("userId");
//		// 加载行情数据
//		HashMap reqMap = new HashMap();
//		reqMap = HttpUtil.buildParameterMap(getRequest());
		reqMap.put("userId", userId);
		String result = service.rechargeAdd(reqMap);
//		hmRetrun = new HashMap<String, String>();
		hmRetrun.put("retult", sHtmlText);
		return SUCCESS;
	}
	
	@Action(value = "addUserFund")
	public String addUserFund() {
		HttpServletRequest request = getRequest();
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		logger.debug("手动充值,{}",param.toString());
		HttpSession session = getSession();
//		// 加载行情数据
		String result = service.addUserFund(param);
//		hmRetrun.put("retult", sHtmlText);
		result="true";
		TradeUtils.ajaxStr(getResponse(), result);
		return null;
	}

	@Action(value = "drawAdd", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/trade/withdraw.jsp") })
	public String drawAdd() {
		//
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();
		String userId = (String) session.getAttribute("userId");
		// 加载行情数据
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		reqMap.put("userId", userId);
		String result = service.drawAdd(reqMap);
		hmRetrun = new HashMap<String, String>();
		hmRetrun.put("retult", result);
		return SUCCESS;
	}

	/**
	 * 体现
	 * 
	 * @return
	 */
	@Action(value = "withdraw", results = { @Result(name = "success", location = "/WEB-INF/pages/trade/trade/withdraw.jsp") })
	public String withdraw() {
		//
		HttpServletRequest request = getRequest();
		HttpSession session = getSession();

		// 加载行情数据
		HashMap reqMap = new HashMap();
		reqMap = HttpUtil.buildParameterMap(getRequest());
		// MiyinMarket market = service.getMarket();
		// request.setAttribute("market", market);

		return SUCCESS;
	}

}
